package org.jeecg.modules.index;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.minqing.entity.*;
import org.jeecg.modules.minqing.service.*;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

@Slf4j
@Api(tags = "系统首页信息")
@RestController
@RequestMapping("/index")
public class IndexController {
    @Autowired
    private IDepartmentsService departmentsService;
    @Autowired
    private IProjectService projectService;
    @Autowired
    private IIndustryChainService industryChainService;
    @Autowired
    private IFavorablePolicyService favorablePolicyService;
    @Autowired
    private IIndustryTypeService industryTypeService;
    @Autowired
    private IOtherServiceService otherServiceService;

    @Autowired
    private IDynamicNewsService dynamicNewsService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 分页列表查询
     *
     * @param departments
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "部门信息-分页列表查询")
    @ApiOperation(value = "部门信息-分页列表查询", notes = "部门信息-分页列表查询")
    @GetMapping(value = "/departmentList")
    public Result<IPage<Departments>> departmentList(Departments departments,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "1000") Integer pageSize,
                                                     HttpServletRequest req) {
        Result<IPage<Departments>> result = new Result<IPage<Departments>>();
        QueryWrapper<Departments> queryWrapper = QueryGenerator.initQueryWrapper(departments, req.getParameterMap());
        Page<Departments> page = new Page<Departments>(pageNo, pageSize);
        IPage<Departments> pageList = departmentsService.page(page, queryWrapper);
        List<Departments> list = new ArrayList<Departments>();
        if (pageList != null && pageList.getRecords() != null) {
            for (int i = 0; i < pageList.getRecords().size(); i++) {
                Departments departments1 = pageList.getRecords().get(i);
                Project project = new Project();
                project.setDepartment(departments1.getId());
                QueryWrapper<Project> queryWrapper1 = QueryGenerator.initQueryWrapper(project, req.getParameterMap());
                List<Project> listProject = projectService.list(queryWrapper1);
                if (listProject != null && listProject.size() > 0) {
                    departments1.setIsProject("1");
                } else {
                    departments1.setIsProject("0");
                }
                list.add(departments1);
            }
        }


        list.sort(new Comparator<Departments>() {
            @Override
            public int compare(Departments o1, Departments o2) {
                if (StringUtils.isNotBlank(o1.getName()) && StringUtils.isNotBlank(o2.getName())) {
                    int t1 = getSort(o1.getName());
                    int t2 = getSort(o2.getName());
                    return t1 - t2;
                }
                return 0;
            }

            private int getSort(String key) {
                Map<String, Integer> sortMap = new HashMap<>();
                sortMap.put("闽清县", 0);
                sortMap.put("梅城镇", 1);
                sortMap.put("梅溪镇", 2);
                sortMap.put("云龙乡", 3);
                sortMap.put("白中镇", 4);
                sortMap.put("白樟镇", 5);
                sortMap.put("池园镇", 6);
                sortMap.put("坂东镇", 7);
                sortMap.put("东桥镇", 8);
                sortMap.put("金沙镇", 9);
                sortMap.put("省璜镇", 10);
                sortMap.put("塔庄镇", 11);
                sortMap.put("上莲乡", 12);
                sortMap.put("雄江镇", 13);
                sortMap.put("三溪乡", 14);
                sortMap.put("桔林乡", 15);
                sortMap.put("下祝乡", 16);
                return sortMap.get(key);
            }
        });

        pageList.setRecords(list);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 分页列表查询
     *
     * @param otherService
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "其他服务-分页列表查询")
    @ApiOperation(value = "其他服务-分页列表查询", notes = "其他服务-分页列表查询")
    @GetMapping(value = "/otherServiceList")
    public Result<IPage<OtherService>> otherServiceList(OtherService otherService,
                                                        @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                        @RequestParam(name = "pageSize", defaultValue = "1") Integer pageSize,
                                                        HttpServletRequest req) {
        Result<IPage<OtherService>> result = new Result<IPage<OtherService>>();
        QueryWrapper<OtherService> queryWrapper = QueryGenerator.initQueryWrapper(otherService, req.getParameterMap());
        Page<OtherService> page = new Page<OtherService>(pageNo, pageSize);
        IPage<OtherService> pageList = otherServiceService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 分页列表查询
     *
     * @param project
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "项目信息表-分页列表查询")
    @ApiOperation(value = "项目信息表-分页列表查询", notes = "项目信息表-分页列表查询")
    @GetMapping(value = "/projectList")
    public Result<IPage<ResultProject>> projectList(Project project,
                                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
        Result<IPage<ResultProject>> result = new Result<IPage<ResultProject>>();
        //QueryWrapper<Project> queryWrapper = QueryGenerator.initQueryWrapper(project, req.getParameterMap());
        project.setStatus("0");
        Page<Project> page = new Page<Project>(pageNo, pageSize);
        IPage<ResultProject> pageList = projectService.queryListProject(page, project);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "项目信息表-通过id查询")
    @ApiOperation(value = "项目信息表-通过id查询", notes = "项目信息表-通过id查询")
    @GetMapping(value = "/queryProjectById")
    public Result<Project> queryProjectById(@RequestParam(name = "id", required = true) String id) {
        Result<Project> result = new Result<Project>();
        Project project = projectService.getById(id);
        if (ObjectUtil.isEmpty(project)) {
            result.setCode(500);
            result.setSuccess(false);
            result.setMessage("项目不存在");
            return result;
        }
        int browse = project.getBrowse() == null ? 0 : project.getBrowse();
        project.setBrowse(browse + 1);
        projectService.updateById(project);
        Departments departments = departmentsService.getById(project.getDepartment());
        IndustryType industryType = industryTypeService.getById(project.getIndustryType());
        project.setDepartmentName(departments.getName());
        project.setIndustryTypeName(industryType.getName());
        if (project.getPreferentialPolicy() != null) {
            List<FavorablePolicy> policis = favorablePolicyService.queryListByIds(Arrays.asList(project.getPreferentialPolicy().split(",")));
            project.setFavorablePolicys(policis);
        }
        if (project == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(project);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 分页列表查询
     *
     * @param industryChain
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "产业链信息-分页列表查询")
    @ApiOperation(value = "产业链信息-分页列表查询", notes = "产业链信息-分页列表查询")
    @GetMapping(value = "/industryChainList")
    public Result<IPage<IndustryChain>> industryChainList(IndustryChain industryChain,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "1000") Integer pageSize,
                                                          HttpServletRequest req) {
        Result<IPage<IndustryChain>> result = new Result<IPage<IndustryChain>>();
        QueryWrapper<IndustryChain> queryWrapper = QueryGenerator.initQueryWrapper(industryChain, req.getParameterMap());
        Page<IndustryChain> page = new Page<IndustryChain>(pageNo, pageSize);
        IPage<IndustryChain> pageList = industryChainService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 通过id查询产业链信息
     *
     * @param id
     * @return
     */
    @AutoLog(value = "产业链信息-通过id查询")
    @ApiOperation(value = "产业链信息-通过id查询", notes = "产业链信息-通过id查询")
    @GetMapping(value = "/queryIndustryChainById")
    public Result<IndustryChain> queryIndustryChainById(@RequestParam(name = "id", required = true) String id) {
        Result<IndustryChain> result = new Result<IndustryChain>();
        IndustryChain industryChain = industryChainService.getById(id);
        if (industryChain == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(industryChain);
            result.setSuccess(true);
        }
        return result;
    }


    /**
     * 分页列表查询
     *
     * @param favorablePolicy
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "优惠政策-分页列表查询")
    @ApiOperation(value = "优惠政策-分页列表查询", notes = "优惠政策-分页列表查询")
    @GetMapping(value = "/favorablePolicyList")
    public Result<IPage<FavorablePolicy>> favorablePolicyList(FavorablePolicy favorablePolicy,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "1000") Integer pageSize,
                                                              HttpServletRequest req) {
        Result<IPage<FavorablePolicy>> result = new Result<IPage<FavorablePolicy>>();
        QueryWrapper<FavorablePolicy> queryWrapper = QueryGenerator.initQueryWrapper(favorablePolicy, req.getParameterMap());
        Page<FavorablePolicy> page = new Page<FavorablePolicy>(pageNo, pageSize);
        IPage<FavorablePolicy> pageList = favorablePolicyService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 列表查询
     *
     * @return
     */
    @AutoLog(value = "优惠政策-列表查询")
    @ApiOperation(value = "优惠政策-列表查询", notes = "优惠政策-列表查询")
    @GetMapping(value = "/favorablePolicyTree")
    public Result<List<FavorablePolicy>> favorablePolicyTree() {
        Result<List<FavorablePolicy>> result = new Result<List<FavorablePolicy>>();
        List<FavorablePolicy> list = favorablePolicyService.builTree();
        result.setSuccess(true);
        result.setResult(list);
        return result;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "优惠政策-通过id查询")
    @ApiOperation(value = "优惠政策-通过id查询", notes = "优惠政策-通过id查询")
    @GetMapping(value = "/queryFavorablePolicyById")
    public Result<FavorablePolicy> queryFavorablePolicyById(@RequestParam(name = "id", required = true) String id) {
        Result<FavorablePolicy> result = new Result<FavorablePolicy>();
        FavorablePolicy favorablePolicy = favorablePolicyService.getById(id);
        if (favorablePolicy == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(favorablePolicy);
            result.setSuccess(true);
        }
        return result;
    }

    /**
     * 其他服务通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "其他服务通过id查询")
    @ApiOperation(value = "其他服务通过id查询", notes = "其他服务通过id查询")
    @GetMapping(value = "/queryOtherById")
    public Result<OtherService> queryOtherById(@RequestParam(name = "id", required = true) String id) {
        Result<OtherService> result = new Result<OtherService>();
        OtherService otherService = otherServiceService.getById(id);
        if (otherService == null) {
            result.error500("未找到对应实体");
        } else {
            result.setResult(otherService);
            result.setSuccess(true);
        }
        return result;
    }

    @GetMapping(value = "/downloadFile")
    private String downloadFile(@RequestParam(name = "fileName", required = false) String fileName, HttpServletResponse response) {
        String downloadFilePath = "E:\\minqingzs\\img\\";//被下载的文件在服务器中的路径,
        //String fileName = "";//被下载文件的名称
        if (fileName == null || fileName.equals("")) {
            return "文件不存在";
        }
        File file = new File(downloadFilePath + fileName);
        if (file.exists()) {
            response.setContentType("application/force-download");// 设置强制下载不打开            
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                return "下载成功";
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "下载失败";
    }


    @ApiOperation(value = "招商工作动态-分页列表查询", notes = "招商工作动态-分页列表查询")
    @GetMapping(value = "/dynamicNewsList")
    public Result<IPage<DynamicNews>> queryPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                    HttpServletRequest req) {
//        Result<IPage<DynamicNews>> result = new Result<IPage<DynamicNews>>();
//        LambdaQueryWrapper<DynamicNews> queryWrapper = new LambdaQueryWrapper();
//        queryWrapper.eq(DynamicNews::getStatus, 1);
//        Page<DynamicNews> page = new Page<DynamicNews>(pageNo, pageSize);
//        IPage<DynamicNews> pageList = dynamicNewsService.page(page, queryWrapper);
//        if (pageList != null) {
//            List<DynamicNews> list = pageList.getRecords();
//            list.sort(new Comparator<DynamicNews>() {
//                @Override
//                public int compare(DynamicNews o1, DynamicNews o2) {
//                    if (StringUtils.isNotBlank(o1.getSort()) && StringUtils.isNotBlank(o2.getSort())) {
//                        return Integer.valueOf(o1.getSort()) - Integer.valueOf(o2.getSort());
//                    }
//                    return 0;
//                }
//            });
//        }
//        result.setSuccess(true);
//        result.setResult(pageList);
        DynamicNews dynamicNews = new DynamicNews();
        Result<IPage<DynamicNews>> result = new Result<IPage<DynamicNews>>();
        Page<DynamicNews> page = new Page<DynamicNews>(pageNo, pageSize);
        IPage<DynamicNews> pageList = dynamicNewsService.getPage(page, dynamicNews);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }



    public Result<?>  test(){
        String search = "陈志";
        LambdaQueryWrapper<SysUser> qw = new LambdaQueryWrapper<>();


        return Result.ok();
    }


}
